(function(UI,DataHelper){
	//define control flow
	var flow = {
		init: function (pEditor, op) {
			
		},
		build: function (pEditor, op) {
			// 创建属性编辑器
			helper.build(pEditor, op);
			// 是否创建属性编辑器的操作栏
			op.buildOperate && helper.buildOperate(pEditor, op);
		},
		bindEvent: function (pEditor, op) {
			// 收缩按钮事件
			pEditor._reIniting || pEditor.dom.delegate('.ccay-prop-open', 'click', function () {
				var title = $(this).toggleClass('prop-close'),
					tr = title.parent().parent(),
					deep = tr.attr("deep"),
					opened = !title.hasClass('prop-close');
				title.children('a').toggleClass('close');
				helper.toggleProp(tr, opened);
			});
			// 操作栏中按钮的操作事件
			helper.bindOperate(pEditor, op);
		},
		complete: function (pEditor, op) {
			// 给标题添加tip提示信息
			pEditor.dom.find('.ccay-prop-name > span').tip({global:true,offset:true});
		}
	};
	//define control manager
	var manager = {
		// 设值
		setValue: function (data) {
			Ccay.Control.setValue(this.dom, this.op.modal, data, "edit");
		},
		getProp :function(propEditor){
			var field = DataHelper.getObj(propEditor.attr("mapping"),this.op.modal,true);
			return Ccay.Control.get("edit").getValue(propEditor,field);
		},
		// 重置
		reset: function () {
			this.setValue(this.op.config);
		},
		// 设置默认值
		setDefault:function () {
			this.setValue(this.op.defConfig);
		},
		// 获取值
		getValue:function () {
			return Ccay.Control.getValue(this.dom, this.op.modal, "edit");
		},
		// 保存
		save: function () {
			if (this.valid()) {
				var conf = this.getValue(),
					data = this.op.getChanged === false ? conf : DataHelper.getDataChange(conf, this.op.defConfig, this.op.arrKeys);
				if (this.op.fnSave && this.op.fnSave(data) !== false) {
					return true;
				}
			}
			return false;
		},
		reInit:function(op){
			this.dom.empty();
			return this.base.reInit.call(this,op);
		},
		valid:function(){
			return Ccay.Control.valid(this.dom);
		},
		find:function(filter){
			return this.dom.find(filter);
		}
	};
	
	//define inner functions
	//liujian 2014/1/22 anniu
	var helper = UI.PropEditor= {
		operateButtons: {
			save: {
				//type: "input", // 默认button样式
				type:"imgBtn",
	      	    icon:"save",
	      	    cls:"ccay-icon",
	      	    css:"ccay-botton-main",
		    	text: "ccay.common.button.save",
				attr: { 
					ecode: "save"
				}
			},
			reset: {
				//type: "input", // 默认button样式
				type:"imgBtn",
				icon:"reset",
				cls:"ccay-icon",
    			text: "ccay.common.button.reset",
		    	attr: {
		    		ecode: "reset"
		    	}
			},
			defalutConfig: {
				//type: "input", // 默认button样式
				type:"imgBtn",
				icon:"confirm",
				cls:"ccay-icon",
    			text: "ccay.common.button.defalutConfig",
		    	attr: {
		    		ecode: "default"
		    	}
			},
			cancel: {
				//type: "input", // 默认button样式
				type:"imgBtn",
				icon:"cancel",
				cls:"ccay-icon",
				text: "ccay.common.button.cancel",
				click: function () {
					$(this).parent().parent().parent().manager().close();
				}
			}
		},
		// 创建属性编辑器
		build: function (pEditor, op) {
			op.props.ePropName = op.title ? $i18n(op.title) : "";
			op.props.ePropDeep = 0;
			op.defConfig = {};
			var modalName = 'prop',
				// 生成布局
				layout = Ccay.ViewLayout.build(op.layout || modalName),
				container;
				
			
			// 创建内容布局模板
			if(op.group)
			{
				layout = Ccay.ViewLayout.build(op.layout || 'prop-group');
				helper.createByGroup(op.props, layout, modalName, op.defConfig,op.group);
				container = $.create("dl", "ccay-propgroup");
			}
			else
			{
				layout = Ccay.ViewLayout.build(op.layout || modalName);
				helper.create(op.props, layout, modalName, op.defConfig);
				container =$.create("table", "ccay-table");
			}

			container.html(layout.html.join("")).appendTo(pEditor.dom.addClass("ccay-prop"));
			layout.end();
			
			var modal = op.modal =  Ccay.Modal.create({
				modalName:modalName,
				fields:op.props,
				initField:false
			}); 
			
			this.buildView(pEditor, op,modal);
			
			
			//op.config = $.extend(true,{},op.defConfig,op.config);
			var oldConfig = $.extend(true,{},op.defConfig);
			// 应用改变的数据
			op.config && DataHelper.applyChangeData(oldConfig,op.config,op.arrKeys);
			op.config = oldConfig;
			
			
			// 设置属性的数据
			modal.setData($.extend(true,{},op.config));
			// 创建每个属性的编辑器
			Ccay.Control.build(pEditor.dom, modal, 'edit');
		},
		// 创建内容布局模板
		create: function (props, layout, namespance, config) {
			if (props)
			{
				// 生成开始部分
				props.ePropName && layout.beginPart(props);
				for(var name in props)
				{
					var prop = props[name];
					if(prop)
					{
						if(name.indexOf("eProp") < 0)
						{
							prop.ePropField = name;
							if(!$.isPlainObject(prop))
							{
								// 给属性添加类型及默认值
								prop = props[name] = helper.buildProp(prop);
							}
							prop.ePropName = prop.ePropName ? $i18n(prop.ePropName).encode() : name;
							prop.ePropDesc && (prop.ePropDesc = $i18n(prop.ePropDesc).encode());
							
							var newNamespance = namespance + "." + name;
							prop.ePropDeep = props.ePropDeep + 1;
							prop.ePropPadding = prop.ePropDeep * 20;
							
							if((prop.type && typeof(prop.type) == 'string') || prop.ePropConf)
							{
								prop.field = newNamespance.substring(5);
								if(prop.ePropConf)
								{
									config[name] = prop.ePropConf;
									delete prop.ePropConf;
								}
								// 初始化属性
								Ccay.Control.initField(prop);
								// 创建编辑器的容器
								var content = Ccay.Control.buildCtrTag(newNamespance);
								// 将容器添加到布局中
								layout.append(prop, content);
							}
							else
							{
								var newConfig = config[name] = {};
								arguments.callee(prop, layout, newNamespance, newConfig);
							}
						}
					}
				}
				// 生成结束部分
				layout.endPart(props);
			}
		},
		// 根据分组配置生成内容布局模板
		createByGroup: function (props, layout, namespance, config,groups) {
			if (props)
			{
				var propConfig;
				// 生成开始部分
				$.each(groups,function(n,group){
					if(group)
					{
						layout.beginPart(group);
						$.each(group,function(i,itemName){
							propConfig = DataHelper.getObj(itemName,props);
							propConfig.field = itemName;
							//设置默认值
							if(propConfig.value != null)
								 DataHelper.setObj(itemName,config,propConfig.value) ;
							// 初始化属性
							Ccay.Control.initField(propConfig);
							// 创建编辑器的容器
							var content = Ccay.Control.buildCtrTag(namespance + '.' + itemName);
							// 将容器添加到布局中
							layout.append(propConfig, content);
						});
						layout.endPart();
					}
				})
			}
		},
		// 给属性添加类型及默认值
		buildProp: function (value) {
			var prop = {};
			if (value != null)
			{
				prop.type = typeof(value);
				prop.ePropConf = value;
			}
			else
			{
				prop.type = 'string';
			}
			return prop;
		},
		buildView:function(pEditor,op,modal){
			if(op.changeHandler)
			{
				modal.bindChange("everyChange",function(name,value,oldValue,view){
					var handler = op.changeHandler[name];
					if(handler)
					{
						handler.call(view,name,value,oldValue);
					}
				});
				pEditor.controller = new Ccay.Controller({
					dom:pEditor.dom,
					modal:modal,
					changeTrigger:true
				});
			}
		},
		buildButton:function(btns){
			var buttons = [],btnConfig = helper.operateButtons; 
			$.each(btns,function(i,name){
				buttons.push($.extend(true,{},btnConfig[name]));
			})
			return buttons;
		},
		// 创建属性编辑器的操作栏
		buildOperate: function (pEditor, op) {
			var panel = $.create("div", "ccay-operate"),
				toolOp = {};
			// 设置工具栏的按钮
			toolOp.items = op.buttons || helper.buildButton(["save","reset","defalutConfig"]);
			// 创建操作工具栏
			panel.ccayToolbar(toolOp).appendTo(pEditor.dom);
		},
		// 操作栏中按钮的操作事件
		bindOperate: function (pEditor, op) {
			if (op.buildOperate) {
				pEditor.dom.children('.ccay-operate').delegate('[ecode]', 'click', function () {
					var btn = $(this),
						type = btn.attr('ecode');
					helper.operate(btn.parent().parent().parent(), type);
				});
			} else {
				pEditor.dom.parent().next().delegate('[ecode]', 'click', function () {
					var btn = $(this), type = btn.attr('ecode');
					// 解决数据量很大时，loading不出来的情况
					if (op.showLoading && type == "save") {
						Ccay.UI.openMainLoading();
						setTimeout(function () {
				        	if (helper.operate(btn.parent().parent().prev().children(), type)) {
				        		btn.parent().parent().parent().manager().close();
				        	}
				     	} ,100);
					} else {
						if (helper.operate(btn.parent().parent().prev().children(), type) && type == "save") {
							btn.parent().parent().parent().manager().close();
						}
					}
				});
			}
		},
		operate: function (editor, operate) {
			switch (operate)
			{
				case 'save':
					return editor.manager().save();
					break;
				case 'reset':
					editor.manager().reset();
					break;
				case 'default':
					editor.manager().setDefault();
					break;	
			}
		},
		getDeep: function (tr) {
			return tr.attr('deep') * 1;
		},
		toggleProp: function (tr, opened) {
			var parentDeep = this.getDeep(tr);
			tr = tr.next();
			if (tr.length) {
				var deep = this.getDeep(tr);
				while (parentDeep < deep)
				{
					tr.toggle(opened);
					tr = tr.next();
					if(tr && tr.length)
						deep = this.getDeep(tr);
					else
						return;
				}
			}
		}
	};
	
	//create XControl
	var XPropEditor = UI.XControl("XPropEditor", flow, null, manager);
	
	// create jquery plugin
	$.fn.propEditor = function (op) {
		new XPropEditor (this, op);
		return this.manager();
	}
	// 添加tableEditor编辑器
	Ccay.Editor.add("tableEditor",{
		build:function(container,op){
			container.css('display', "block");
			var ctr = $.create("div", 'control-composite', "propGrid").appendTo(container);
			return ctr.igrid($.extend(true, {
					height:255,
					editMode: true,
					allowSort: false,
					showSeq: false,
					showPager: false,
					dataCopy: true,
					customSetting: false,
					showToolBar: false,
					colsort: false,
					storageOp: {innerStatus: false}
			}, op));
		}
	});
	
	// 添加prop布局
	Ccay.ViewLayout.add("prop", {
		partStart : '<tr deep="${ePropDeep}"><th class="ccay-prop-title" colspan=2 style="padding-left:${ePropPadding}px"><span class="ccay-prop-open"><a class="ccay-icon open"></a>${ePropName}</span></th></tr>',
		layout :'<tr deep="${item.ePropDeep}"><td style="padding-left:${item.ePropPadding}px" class="ccay-prop-name ${item.titleMark}"><span title="${item.ePropDesc}">${item.ePropName}</span></td><td class="ccay-prop-input">${item}</td></tr>',
		//partEnd : ''
		setItemOp:function(item){
			Ccay.Modal.isRequiredField(item) && (item.titleMark = 'required');
			return item;
		},
		checkPartEnd:function(item){
			item.titleMark && delete item.titleMark;
		}
	}).
	add("prop-simple",{
		layout :'<tr><td class="ccay-prop-name ${item.titleMark}"><span title="${item.ePropDesc}">${item.ePropName}</span></td><td class="ccay-prop-input">${item}</td></tr>'
		,partEnd : '</tbody>',
		beginPart:function(item){
			item.ePropField && this.html.push("<tbody group='" + item.ePropField + "'>");
		},
		//添加区域结束模板
		endPart:function(item){
			item.ePropField && this.html.push(this.partEnd);
		},
		setItemOp:function(item){
			Ccay.Modal.isRequiredField(item) && (item.titleMark = 'required');
			return item;
		},
		checkPartEnd:function(item){
			item.titleMark && delete item.titleMark;
		}
	}).
	add("prop-group",{
		partStart : '<dt>${group}</dt><dd><ul>',
		layout :'<li class="ccay-prop-item" _item="${item.field}"><span  class="ccay-prop-title ${item.titleMark}" title="${item.desc}">${item.name}</span><samp class="ccay-prop-input">${item}</samp></li>'
		,partEnd : '</ul></dd>',
		setPartOp:function(group){
			return {group : group.name};
		},
		setItemOp:function(item){
			Ccay.Modal.isRequiredField(item) && (item.titleMark = 'required');
			return item;
		}
	});
	
	// 弹出框类型的属性编辑器
	Ccay.UI.openPropEditor = function (op,profileOpen) {
		var profileContent = profileOpen ? "<div id='profileDIV' style='margin-bottom:2px;'><label i18nKey='ccay.common.label.profile' class='init i18n' /><font color='red'>&nbsp;*</font>&nbsp;<input id='profileText' class='required' type='text'/></div>":""; 
		Ccay.UI.dialog(null, op.dialogTitle, {
			width: op.dialogWidth,
			height: op.dialogHeight,
			target:op.dialogTarget,
			content: "<form>"+profileContent+"</form>",
			fnLoad: function (dialog)
			{
				this.getBody().children().propEditor(op);
			},
			toolbar: {
				items: op.buttons || helper.buildButton(["save","reset","defalutConfig","cancel"])
			}
		});
	}
	
})(Ccay.UI,Ccay.DataHelper);
